package site.psvm;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author leo
 * 泛型-泛型方法
 */
public class Demo3 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        System.out.println("reverseMethod(list) = " + reverseMethod(list));

        //泛型方法 数组拷贝
        Integer[] arr = {1,2,3,4,5};
        Integer[] integers = copyArray(arr);
    }

    public static <E> E[] copyArray(E[]arr){
        //class.getComponentType() 获取数组元素的类型
        Class<?> componentType = arr.getClass().getComponentType();
        E[] newArr = (E[]) Array.newInstance(componentType,arr.length);
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

   public static <T> List<T> reverseMethod(List<T> list){
       List<T> reverseList = new ArrayList<>();
       for (int i = list.size() - 1; i >= 0; i--) {
           reverseList.add(list.get(i));
       }
        return reverseList;
    }
}
